{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Training a Classifier\n",
        "\n",
        "This is it. You have seen how to define neural networks, compute loss and make\n",
        "updates to the weights of the network.\n",
        "\n",
        "Now you might be thinking,\n",
        "\n",
        "## What about data?\n",
        "\n",
        "Generally, when you have to deal with image, text, audio or video data,\n",
        "you can use standard python packages that load data into a numpy array.\n",
        "Then you can convert this array into a `torch.*Tensor`.\n",
        "\n",
        "- For images, packages such as Pillow, OpenCV are useful\n",
        "- For audio, packages such as scipy and librosa\n",
        "- For text, either raw Python or Cython based loading, or NLTK and\n",
        "  SpaCy are useful\n",
        "\n",
        "Specifically for vision, we have created a package called\n",
        "`torchvision`, that has data loaders for common datasets such as\n",
        "ImageNet, CIFAR10, MNIST, etc. and data transformers for images, viz.,\n",
        "`torchvision.datasets` and `torch.utils.data.DataLoader`.\n",
        "\n",
        "This provides a huge convenience and avoids writing boilerplate(样板) code.\n",
        "\n",
        "For this tutorial, we will use the CIFAR10 dataset.\n",
        "It has the classes: ‘airplane’, ‘automobile’, ‘bird’, ‘cat’, ‘deer’,\n",
        "‘dog’, ‘frog’, ‘horse’, ‘ship’, ‘truck’. The images in CIFAR-10 are of\n",
        "size 3x32x32, i.e. 3-channel color images of 32x32 pixels in size.\n",
        "\n",
        "<!-- .. figure:: /_static/img/cifar10.png\n",
        "   :alt: cifar10 -->\n",
        "\n",
        "![](images/cifar10.png)\n",
        "\n",
        "cifar10\n",
        "\n",
        "## Training an image classifier\n",
        "\n",
        "We will do the following steps in order:\n",
        "\n",
        "1. Load and normalize the CIFAR10 training and test datasets using\n",
        "   `torchvision`\n",
        "2. Define a Convolutional Neural Network\n",
        "3. Define a loss function\n",
        "4. Train the network on the training data\n",
        "5. Test the network on the test data\n",
        "\n",
        "### 1. Load and normalize CIFAR10\n",
        "\n",
        "Using `torchvision`, it’s extremely easy to load CIFAR10.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import torch\n",
        "import torchvision\n",
        "import torchvision.transforms as transforms\n",
        "from torch.utils.data import DataLoader\n",
        "from torch import (Tensor)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The output of torchvision datasets are PILImage images of range [0, 1].\n",
        "We transform them to Tensors of normalized range [-1, 1].\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "<div class=\"alert alert-info\"><h4>Note</h4><p>If running on Windows and you get a BrokenPipeError, try setting\n",
        "    the num_worker of torch.utils.data.DataLoader() to 0.</p></div>\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "#\n",
        "#\n",
        "ROOT = \"E:/sfxData/DeepLearning\"\n",
        "\n",
        "transform = transforms.Compose(\n",
        "    [transforms.ToTensor(),\n",
        "     transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))])\n",
        "\n",
        "batch_size = 4\n",
        "\n",
        "# train\n",
        "trainset = torchvision.datasets.CIFAR10(\n",
        "    root=ROOT,\n",
        "    train=True,\n",
        "    download=True,\n",
        "    transform=transform)\n",
        "\n",
        "trainloader = DataLoader(\n",
        "    trainset,\n",
        "    batch_size=batch_size,\n",
        "    shuffle=True,\n",
        "    num_workers=2)\n",
        "\n",
        "# test\n",
        "testset = torchvision.datasets.CIFAR10(\n",
        "    root=ROOT,\n",
        "    train=False,\n",
        "    download=True,\n",
        "    transform=transform)\n",
        "\n",
        "testloader = DataLoader(\n",
        "    testset,\n",
        "    batch_size=batch_size,\n",
        "    shuffle=False,\n",
        "    num_workers=2)\n",
        "\n",
        "classes = ('plane', 'car', 'bird', 'cat', 'deer',\n",
        "           'dog', 'frog', 'horse', 'ship', 'truck')\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let us show some of the training images, for fun.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "# functions to show an image\n",
        "\n",
        "\n",
        "def imshow(img: Tensor):\n",
        "    img = (img+1) / 2.0     # unnormalize [-1,1] => [0,1]\n",
        "    npimg = img.numpy()\n",
        "    plt.imshow(np.transpose(npimg, (1, 2, 0)))  # 将 [3,32,128]-->[32,128,3]\n",
        "    plt.show()\n",
        "\n",
        "\n",
        "# get some random training images\n",
        "dataiter = iter(trainloader)\n",
        "images, labels = next(dataiter)\n",
        "\n",
        "# print(labels)        # [8, 0, 2, 9]     对应 4 个样本的标签\n",
        "# print(images.shape)  # [4, 3, 32, 32]   表示四张（3，32，32）的图片，cifar中的图片\n",
        "\n",
        "# make_grid:将多张图片组合成一张图片\n",
        "# image_batch = torchvision.utils.make_grid(images, padding=0)  # [3, 32, 128]\n",
        "image_batch = torchvision.utils.make_grid(images, padding=2)  # [3, 36, 138]\n",
        "# print(image_batch.shape)\n",
        "\n",
        "\n",
        "# show images\n",
        "imshow(image_batch)\n",
        "\n",
        "# print labels\n",
        "print(' '.join(f'{classes[labels[j]]:5s}' for j in range(batch_size)))\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 2. Define a Convolutional Neural Network\n",
        "\n",
        "Copy the neural network from the Neural Networks section before and modify it to\n",
        "take 3-channel images (instead of 1-channel images as it was defined).\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import torch.nn as nn\n",
        "import torch.nn.functional as F\n",
        "\n",
        "# [3, 36, 138]\n",
        "class Net(nn.Module):\n",
        "    def __init__(self):\n",
        "        super().__init__()\n",
        "        self.conv1 = nn.Conv2d(3, 6, 5)         # out = [6,32,32]\n",
        "        self.pool = nn.MaxPool2d(2, 2)          # out = [6,16,16]\n",
        "        self.conv2 = nn.Conv2d(6, 16, 5)        # out = [16,16,16]\n",
        "        self.fc1 = nn.Linear(16 * 5 * 5, 120)   # ?\n",
        "        self.fc2 = nn.Linear(120, 84)\n",
        "        self.fc3 = nn.Linear(84, 10)\n",
        "\n",
        "    def forward(self, x):\n",
        "        x = self.pool(F.relu(self.conv1(x)))\n",
        "        x = self.pool(F.relu(self.conv2(x)))\n",
        "        x = torch.flatten(x, 1)  # flatten all dimensions except batch\n",
        "        x = F.relu(self.fc1(x))\n",
        "        x = F.relu(self.fc2(x))\n",
        "        x = self.fc3(x)\n",
        "        return x\n",
        "\n",
        "\n",
        "net = Net()\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 3. Define a Loss function and optimizer\n",
        "\n",
        "Let's use a Classification Cross-Entropy loss and SGD with momentum.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import torch.optim as optim\n",
        "\n",
        "criterion = nn.CrossEntropyLoss()\n",
        "optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 4. Train the network\n",
        "\n",
        "This is when things start to get interesting.\n",
        "We simply have to loop over our data iterator, and feed the inputs to the\n",
        "network and optimize.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# loop over the dataset multiple times\n",
        "for epoch in range(2):\n",
        "    running_loss = 0.0\n",
        "    for i, data in enumerate(trainloader, 0):\n",
        "        # get the inputs; data is a list of [inputs, labels]\n",
        "        inputs, labels = data\n",
        "\n",
        "        # zero the parameter gradients\n",
        "        optimizer.zero_grad()\n",
        "\n",
        "        # forward + backward + optimize\n",
        "        outputs = net(inputs)\n",
        "        loss = criterion(outputs, labels)\n",
        "        loss.backward()\n",
        "        optimizer.step()\n",
        "\n",
        "        # print statistics\n",
        "        running_loss += loss.item()\n",
        "        if i % 2000 == 1999:    # print every 2000 mini-batches\n",
        "            print(f'[{epoch + 1}, {i + 1:5d}] loss: {running_loss / 2000:.3f}')\n",
        "            running_loss = 0.0\n",
        "\n",
        "print('Finished Training')\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let's quickly save our trained model:\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "PATH = './cifar_net.pth'\n",
        "torch.save(net.state_dict(), PATH)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "See [here](https://pytorch.org/docs/stable/notes/serialization.html)\n",
        "for more details on saving PyTorch models.\n",
        "\n",
        "### 5. Test the network on the test data\n",
        "\n",
        "We have trained the network for 2 passes over the training dataset.\n",
        "But we need to check if the network has learnt anything at all.\n",
        "\n",
        "We will check this by predicting the class label that the neural network\n",
        "outputs, and checking it against the ground-truth. If the prediction is\n",
        "correct, we add the sample to the list of correct predictions.\n",
        "\n",
        "Okay, first step. Let us display an image from the test set to get familiar.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "dataiter = iter(testloader)\n",
        "images, labels = next(dataiter)\n",
        "\n",
        "# print images\n",
        "imshow(torchvision.utils.make_grid(images))\n",
        "print('GroundTruth: ', ' '.join(f'{classes[labels[j]]:5s}' for j in range(4)))\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Next, let's load back in our saved model (note: saving and re-loading the model\n",
        "wasn't necessary here, we only did it to illustrate how to do so):\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "net = Net()\n",
        "net.load_state_dict(torch.load(PATH))\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Okay, now let us see what the neural network thinks these examples above are:\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "outputs = net(images)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The outputs are energies for the 10 classes.\n",
        "The higher the energy for a class, the more the network\n",
        "thinks that the image is of the particular class.\n",
        "So, let's get the index of the highest energy:\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "_, predicted = torch.max(outputs, 1)\n",
        "\n",
        "print('Predicted: ', ' '.join(f'{classes[predicted[j]]:5s}'\n",
        "                              for j in range(4)))\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The results seem pretty good.\n",
        "\n",
        "Let us look at how the network performs on the whole dataset.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "correct = 0\n",
        "total = 0\n",
        "# since we're not training, we don't need to calculate the gradients for our outputs\n",
        "with torch.no_grad():\n",
        "    for data in testloader:\n",
        "        images, labels = data\n",
        "        # calculate outputs by running images through the network\n",
        "        outputs = net(images)\n",
        "        # the class with the highest energy is what we choose as prediction\n",
        "        _, predicted = torch.max(outputs.data, 1)\n",
        "        total += labels.size(0)\n",
        "        correct += (predicted == labels).sum().item()\n",
        "\n",
        "print(\n",
        "    f'Accuracy of the network on the 10000 test images: {100 * correct // total} %')\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "That looks way better than chance, which is 10% accuracy (randomly picking\n",
        "a class out of 10 classes).\n",
        "Seems like the network learnt something.\n",
        "\n",
        "Hmmm, what are the classes that performed well, and the classes that did\n",
        "not perform well:\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# prepare to count predictions for each class\n",
        "correct_pred = {classname: 0 for classname in classes}\n",
        "total_pred = {classname: 0 for classname in classes}\n",
        "\n",
        "# again no gradients needed\n",
        "with torch.no_grad():\n",
        "    for data in testloader:\n",
        "        images, labels = data\n",
        "        outputs = net(images)\n",
        "        _, predictions = torch.max(outputs, 1)\n",
        "        # collect the correct predictions for each class\n",
        "        for label, prediction in zip(labels, predictions):\n",
        "            if label == prediction:\n",
        "                correct_pred[classes[label]] += 1\n",
        "            total_pred[classes[label]] += 1\n",
        "\n",
        "\n",
        "# print accuracy for each class\n",
        "for classname, correct_count in correct_pred.items():\n",
        "    accuracy = 100 * float(correct_count) / total_pred[classname]\n",
        "    print(f'Accuracy for class: {classname:5s} is {accuracy:.1f} %')\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Okay, so what next?\n",
        "\n",
        "How do we run these neural networks on the GPU?\n",
        "\n",
        "## Training on GPU\n",
        "\n",
        "Just like how you transfer a Tensor onto the GPU, you transfer the neural\n",
        "net onto the GPU.\n",
        "\n",
        "Let's first define our device as the first visible cuda device if we have\n",
        "CUDA available:\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n",
        "\n",
        "# Assuming that we are on a CUDA machine, this should print a CUDA device:\n",
        "\n",
        "print(device)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The rest of this section assumes that `device` is a CUDA device.\n",
        "\n",
        "Then these methods will recursively go over all modules and convert their\n",
        "parameters and buffers to CUDA tensors:\n",
        "\n",
        ".. code:: python\n",
        "\n",
        "    net.to(device)\n",
        "\n",
        "Remember that you will have to send the inputs and targets at every step\n",
        "to the GPU too:\n",
        "\n",
        ".. code:: python\n",
        "\n",
        "        inputs, labels = data[0].to(device), data[1].to(device)\n",
        "\n",
        "Why don't I notice MASSIVE speedup compared to CPU? Because your network\n",
        "is really small.\n",
        "\n",
        "**Exercise:** Try increasing the width of your network (argument 2 of\n",
        "the first `nn.Conv2d`, and argument 1 of the second `nn.Conv2d` –\n",
        "they need to be the same number), see what kind of speedup you get.\n",
        "\n",
        "**Goals achieved**:\n",
        "\n",
        "- Understanding PyTorch's Tensor library and neural networks at a high level.\n",
        "- Train a small neural network to classify images\n",
        "\n",
        "## Training on multiple GPUs\n",
        "\n",
        "If you want to see even more MASSIVE speedup using all of your GPUs,\n",
        "please check out :doc:`data_parallel_tutorial`.\n",
        "\n",
        "## Where do I go next?\n",
        "\n",
        "- :doc:`Train neural nets to play video games </intermediate/reinforcement_q_learning>`\n",
        "- `Train a state-of-the-art ResNet network on imagenet`\\_\n",
        "- `Train a face generator using Generative Adversarial Networks`\\_\n",
        "- `Train a word-level language model using Recurrent LSTM networks`\\_\n",
        "- `More examples`\\_\n",
        "- `More tutorials`\\_\n",
        "- `Discuss PyTorch on the Forums`\\_\n",
        "- `Chat with other users on Slack`\\_\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "del dataiter\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.9.9 (tags/v3.9.9:ccb0e6a, Nov 15 2021, 18:08:50) [MSC v.1929 64 bit (AMD64)]"
    },
    "vscode": {
      "interpreter": {
        "hash": "cf18841ace8313d0bc088ca146c17a6c0040e82121d5cb75c0ea07172309253d"
      }
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
